/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.modules.system.service.CoursechapterService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.CourseService;
import me.zhengjie.modules.system.domain.vo.CourseQueryCriteria;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

import static me.zhengjie.utils.TreeDataUtil.convertObjectToMap;

/**
* @description 服务实现
* @author shitou
* @date 2024-04-21
**/
@Service
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    private final CourseMapper courseMapper;

    private final UserMapper userMapper;

    private final CourseandclazzMapper courseandclazzMapper;

    private final TeacherMapper teacherMapper;

    private final DepartmentteacherMapper departmentteacherMapper;

    private final CoursechapterMapper coursechapterMapper;

    private final CoursechapterService coursechapterService;

    private final CourseteacherMapper courseteacherMapper;

    private final CourseteacherassignMapper courseteacherassignMapper;

    public Course queryCourseMsg(Integer id) {
        return courseMapper.findMsg(id);
    }

    public List<Course> queryCourseList(List<Integer> ids){
        System.out.println("==coursechapterList1==");
        return courseMapper.queryCourseList(ids);
    }

    @Override
    public PageResult<Course> queryAll(CourseQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setCreateuserid(currentUser.getId());
        IPage<Course> courseList = courseMapper.findAll(criteria, page);

        List<Integer> courseIds = new ArrayList<>();
        for(Course course: courseList.getRecords()){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("courseId",course.getId());
            course.setCount(courseandclazzMapper.selectCount(queryWrapper));
            courseIds.add(course.getId());
        }
        List<Coursechapter> coursechapterList = new ArrayList<>();
        List<Courseteacher> courseteacherList = new ArrayList<>();
        List<Teacher> teacherList = new ArrayList<>();
        List<Map<String,Object>> list4 = new ArrayList<>();


        if(courseIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseId",courseIds);
            coursechapterList = coursechapterService.list(queryWrapper);

            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("courseId",courseIds);
            courseteacherList = courseteacherMapper.selectList(queryWrapper1);
            List<Integer> teacherIds = new ArrayList<>();
            for(Courseteacher courseteacher:courseteacherList){
                teacherIds.add(courseteacher.getTeacherId());
            }
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("id",teacherIds);
            if(teacherIds.size()!=0){
                teacherList = teacherMapper.selectList(queryWrapper2);
            }

            List<Map<String,Object>> current = new ArrayList<>();
            for(Coursechapter coursechapter :coursechapterList){
                Map<String, Object> map = convertObjectToMap(coursechapter);
                map.put("id",coursechapter.getId());
                map.put("children",current);
                map.put("parentId",coursechapter.getParentId());
                map.put("courseId",coursechapter.getCourseId());
                list4.add(map);
            }
        }

        List<Map<String,Object>> coursechapterList2  = list4.stream().filter(m -> (m.get("parentId") + "").equals("0")).peek(
                (m) -> m.put("children", getChildren(m,list4))
        ).collect(Collectors.toList());

        for(Course course: courseList.getRecords()){
            course.setSectionNum(0);
            course.setChapterNum(0);

            for(Map<String,Object> map:coursechapterList2){

                if((Integer) map.get("courseId") == Math.toIntExact(course.getId())){

                    course.setChapterNum(course.getChapterNum() + 1);
                    for(Map<String,Object> map2: (List<Map<String,Object>>) map.get("children")){
                        if((Integer) map2.get("courseId") == Math.toIntExact(course.getId())){
                            course.setSectionNum(course.getSectionNum() + 1);
                        }
                    }
                }
            }
            course.setAuditAllNum(0);
            course.setAuditNum(0);
            for(Coursechapter coursechapter:coursechapterList){
                if(coursechapter.getCourseId() == course.getId()){
                    course.setAuditAllNum(course.getAuditAllNum() +1);
                    if(coursechapter.getState() !=null && coursechapter.getState() == 2){

                        course.setAuditNum(course.getAuditNum() + 1);
                    }
                }
            }
//            teacherList
            List<Teacher> teacherList1 = new ArrayList<>();
            for(Courseteacher courseteacher:courseteacherList){
                if(courseteacher.getCourseId() == course.getId()){
                    for(Teacher teacher:teacherList){
                        if(Math.toIntExact(teacher.getId()) == courseteacher.getTeacherId()){
                            teacherList1.add(teacher);
                        }
                    }
                }
            }
            course.setTeacherList(teacherList1);
        }
        return PageUtil.toPage(courseList);
    }



    @Override
    public PageResult<Course> queryAllCourse(CourseQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setCreateuserid(currentUser.getId());
        IPage<Course> courseList = courseMapper.findAll(criteria, page);

        List<Integer> courseIds = new ArrayList<>();
        for(Course course: courseList.getRecords()){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("courseId",course.getId());
            course.setCount(courseandclazzMapper.selectCount(queryWrapper));
            courseIds.add(course.getId());
        }
        List<Coursechapter> coursechapterList = new ArrayList<>();
        List<Courseteacherassign> courseteacherList = new ArrayList<>();
        List<Teacher> teacherList = new ArrayList<>();
        List<Map<String,Object>> list4 = new ArrayList<>();


        if(courseIds.size()!=0){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseId",courseIds);
            coursechapterList = coursechapterService.list(queryWrapper);

            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("courseId",courseIds);
            courseteacherList = courseteacherassignMapper.selectList(queryWrapper1);

            List<Integer> teacherIds = new ArrayList<>();
            for(Courseteacherassign courseteacher:courseteacherList){
                teacherIds.add(courseteacher.getUserId());
            }
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("userid",teacherIds);
            if(teacherIds.size()!=0){
                teacherList = teacherMapper.selectList(queryWrapper2);
            }

            List<Map<String,Object>> current = new ArrayList<>();
            for(Coursechapter coursechapter :coursechapterList){
                Map<String, Object> map = convertObjectToMap(coursechapter);
                map.put("id",coursechapter.getId());
                map.put("children",current);
                map.put("parentId",coursechapter.getParentId());
                map.put("courseId",coursechapter.getCourseId());
                list4.add(map);
            }
        }

        List<Map<String,Object>> coursechapterList2  = list4.stream().filter(m -> (m.get("parentId") + "").equals("0")).peek(
                (m) -> m.put("children", getChildren(m,list4))
        ).collect(Collectors.toList());

        for(Course course: courseList.getRecords()){
            course.setSectionNum(0);
            course.setChapterNum(0);

            for(Map<String,Object> map:coursechapterList2){

                if((Integer) map.get("courseId") == Math.toIntExact(course.getId())){

                    course.setChapterNum(course.getChapterNum() + 1);
                    for(Map<String,Object> map2: (List<Map<String,Object>>) map.get("children")){
                        if((Integer) map2.get("courseId") == Math.toIntExact(course.getId())){
                            course.setSectionNum(course.getSectionNum() + 1);
                        }
                    }
                }
            }
//            course.setAuditAllNum(0);
//            course.setAuditNum(0);
//            for(Coursechapter coursechapter:coursechapterList){
//                if(coursechapter.getCourseId() == course.getId()){
//                    course.setAuditAllNum(course.getAuditAllNum() +1);
//                    if(coursechapter.getState() !=null && coursechapter.getState() == 2){
//
//                        course.setAuditNum(course.getAuditNum() + 1);
//                    }
//                }
//            }
//            teacherList
            List<Teacher> teacherList1 = new ArrayList<>();
            for(Courseteacherassign courseteacher:courseteacherList){
                if(courseteacher.getCourseId() == course.getId()){
                    for(Teacher teacher:teacherList){
                        if(Math.toIntExact(teacher.getUserid()) == courseteacher.getUserId()){
                            teacherList1.add(teacher);
                        }
                    }
                }
            }
            course.setTeacherList(teacherList1);
        }
        return PageUtil.toPage(courseList);
    }


    public static List<Map<String,Object>> getChildren(Map<String,Object> root, List<Map<String,Object>> all){
        List<Map<String,Object>> list1 = all.stream().filter(m -> Objects.equals(m.get("parentId"),root.get("id"))).peek(
                (m) -> m.put("children",(getChildren(m,all)))
        ).collect(Collectors.toList());
        return list1;
    }

    @Override
    public PageResult<Course> getCourseList(CourseQueryCriteria criteria, Page<Object> page){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setCreateuserid(currentUser.getId());
        IPage<Course> courseList = courseMapper.findAll(criteria, page);

        for(Course course: courseList.getRecords()){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("courseId",course.getId());
            course.setCount(courseandclazzMapper.selectCount(queryWrapper));
        }


        List<Course> courseList2 = courseList.getRecords();

        List<Integer> courseIds = new ArrayList<>();
        for(Course course:courseList2){
            courseIds.add(course.getId());
        }
        //获取
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("courseId",courseIds);
        List<Coursechapter>  coursechapterList = new ArrayList<>();
        if(courseIds.size()!=0){
            coursechapterList = coursechapterMapper.selectList(queryWrapper);
        }

        for(Course course:courseList2){
            course.setChapterNum(0);
            course.setSectionNum(0);
            for(Coursechapter coursechapter:coursechapterList){
                if(coursechapter.getCourseId() == course.getId()){
                    if(coursechapter.getParentId()!=null){
                        course.setSectionNum(course.getSectionNum()+1);
                    } else {
                        course.setChapterNum(course.getChapterNum()+1);
                    }
                }
            }
        }
        courseList.setRecords(courseList2);

        return PageUtil.toPage(courseList);
    }



    @Override
    public List<Course> queryAll(CourseQueryCriteria criteria){
        return courseMapper.findAll(criteria);
    }

    public List<Course> getTeacherCourseList(CourseQueryCriteria criteria){


        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        //获取教师绑定的课程
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userid",teacher.getUserid());
//        List<Courseteacher> courseteacherList = courseteacherMapper.selectList(queryWrapper1);
        List<Courseteacherassign> courseteacherList = courseteacherassignMapper.selectList(queryWrapper1);

        List<Integer> courseIds = new ArrayList<>();
        for(Courseteacherassign courseteacher:courseteacherList){
            courseIds.add(courseteacher.getCourseId());
        }
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id",courseIds);
        if(criteria.getName()!=null){
            queryWrapper2.like("name",criteria.getName());
        }
        if(criteria.getState2()!=null){
            queryWrapper2.like("state2",criteria.getState2());
        }

        List<Course> courseList =  courseMapper.selectList(queryWrapper2);

        for(Course course: courseList){
            QueryWrapper queryWrapper5 = new QueryWrapper();
            queryWrapper5.eq("courseId",course.getId());
            course.setCount(courseandclazzMapper.selectCount(queryWrapper5));
            courseIds.add(course.getId());
        }
        List<Coursechapter> coursechapterList = new ArrayList<>();
;
        List<Teacher> teacherList = new ArrayList<>();
        List<Map<String,Object>> list4 = new ArrayList<>();


        if(courseIds.size()!=0){
            QueryWrapper queryWrapper6 = new QueryWrapper<>();
            queryWrapper6.in("courseId",courseIds);
            coursechapterList = coursechapterService.list(queryWrapper6);


            List<Integer> teacherIds = new ArrayList<>();
            for(Courseteacherassign courseteacher:courseteacherList){
                teacherIds.add(courseteacher.getUserId());
            }
            QueryWrapper queryWrapper7 = new QueryWrapper<>();
            queryWrapper7.in("userid",teacherIds);
            teacherList = teacherMapper.selectList(queryWrapper7);
            List<Map<String,Object>> current = new ArrayList<>();
            for(Coursechapter coursechapter :coursechapterList){
                Map<String, Object> map = convertObjectToMap(coursechapter);
                map.put("id",coursechapter.getId());
                map.put("children",current);
                map.put("parentId",coursechapter.getParentId());
                map.put("courseId",coursechapter.getCourseId());
                list4.add(map);
            }
        }

        List<Map<String,Object>> coursechapterList2  = list4.stream().filter(m -> (m.get("parentId") + "").equals("0")).peek(
                (m) -> m.put("children", getChildren(m,list4))
        ).collect(Collectors.toList());

        for(Course course: courseList){
            course.setSectionNum(0);
            course.setChapterNum(0);

            for(Map<String,Object> map:coursechapterList2){

                if((Integer) map.get("courseId") == Math.toIntExact(course.getId())){

                    course.setChapterNum(course.getChapterNum() + 1);
                    for(Map<String,Object> map2: (List<Map<String,Object>>) map.get("children")){
                        if((Integer) map2.get("courseId") == Math.toIntExact(course.getId())){
                            course.setSectionNum(course.getSectionNum() + 1);
                        }
                    }
                }
            }
//            course.setAuditAllNum(0);
//            course.setAuditNum(0);
//            for(Coursechapter coursechapter:coursechapterList){
//                if(coursechapter.getCourseId() == course.getId()){
//                    course.setAuditAllNum(course.getAuditAllNum() +1);
//                    if(coursechapter.getState() !=null && coursechapter.getState() == 2){
//
//                        course.setAuditNum(course.getAuditNum() + 1);
//                    }
//                }
//            }
//            teacherList
            List<Teacher> teacherList1 = new ArrayList<>();
            for(Courseteacherassign courseteacher:courseteacherList){
                if(courseteacher.getCourseId() == course.getId()){
                    for(Teacher teacher2:teacherList){
                        if(Math.toIntExact(teacher2.getUserid()) == courseteacher.getUserId()){
                            teacherList1.add(teacher2);
                        }
                    }
                }
            }
            course.setTeacherList(teacherList1);
        }
        return courseList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Course resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        resources.setCreateuserid(Math.toIntExact(currentUser.getId()));


        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        // 将 LocalDateTime 按照定义的格式进行格式化
        String formattedDateTime = now.format(formatter);
        resources.setCreatetime(formattedDateTime);
        save(resources);
    }


    @Transactional(rollbackFor = Exception.class)
    public void createDeparmentCourse(Course resources) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        //查询所在部门
        resources.setCreateuserid(Math.toIntExact(currentUser.getId()));

//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("userId",currentUser.getId());
//        Teacher teacher = teacherMapper.selectOne(queryWrapper);
//
//        QueryWrapper queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("teacherId",teacher.getId());
//        Departmentteacher departmentteacher = departmentteacherMapper.selectOne(queryWrapper2);
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss");
        // 将 LocalDateTime 按照定义的格式进行格式化
        String formattedDateTime = now.format(formatter);
        resources.setCreatetime(formattedDateTime);
        save(resources);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Course resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        resources.setCreateuserid(Math.toIntExact(currentUser.getId()));

        Course course = getById(resources.getId());
        course.copy(resources);
        saveOrUpdate(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Course> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Course course : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", course.getName());
            map.put("创建时间", course.getCreatetime());
            map.put("创建教师", course.getCreateteacherid());
            map.put("创建用户", course.getCreateuserid());
            map.put("封面", course.getCover());
            map.put("开启关闭", course.getIsopen());
            map.put(" lastupdatetime",  course.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}